package com.gywj.race.service;

import com.gywj.race.util.ObjectUtil;
import com.gywj.race.util.oss.OssUtil;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * 管理端Oss存储文件服务类
 *
 * @author ccg
 * @version v1.0.0
 * @since 2018-12-05
 */
@Service
public class OssService {

    @Autowired
    private OssUtil ossUtil;

    /**
     * 单个文件上传
     *
     * @param file 单个文件
     * @return 返回 url
     */
    public String uploadFile(MultipartFile file) {
        try {
            String fileType = this.getFileType(file);
            String url = ossUtil.uploadFile(file, fileType);
            if (ObjectUtil.isNullObj(url)) {
                throw new ServiceException("调用oss存储，上传文件失败");
            }
            return url;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 单个jpg文件上传
     *
     * @param content base64 data jpg
     * @return 返回 url
     */
    public String putDataBase64Jpg(String content) {
        try {
            String url = ossUtil.putDataBase64Jpg(content);
            if (ObjectUtil.isNullObj(url)) {
                throw new ServiceException("调用oss存储，上传文件失败");
            }
            return url;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 单个文件上传(自定义文件名)
     *
     * @param file 单个文件
     * @return 返回 url
     */
    public String uploadFileWithFileName(MultipartFile file, String fileName) {
        try {
            String fileType = this.getFileType(file);
            String url = ossUtil.uploadFile(file, fileType, fileName);
            if (ObjectUtil.isNullObj(url)) {
                throw new ServiceException("调用oss存储，上传文件失败");
            }
            return url;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 单个 图片 文件上传(带压缩)
     *
     * @param file 单个文件
     * @return 返回 url
     */
    public String uploadPicWithCompress(MultipartFile file) {
        try {
            String fileType = this.getFileType(file);
            String url = ossUtil.uploadFile(file, fileType, 0.5f);
            if (ObjectUtil.isNullObj(url)) {
                throw new ServiceException("调用oss存储，上传文件失败");
            }
            return url;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 单个文件更新替换
     *
     * @param file   单个文件
     * @param oldUrl 需要替换的url地址
     * @return 返回url
     */
    public String updateFile(MultipartFile file, String oldUrl) {
        try {
            String fileType = this.getFileType(file);
            String url = ossUtil.updateFile(file, fileType, oldUrl);
            if (ObjectUtil.isNullObj(url)) {
                throw new ServiceException("调用oss存储，更新/替换文件失败");
            }
            return url;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 单个 图片 文件更新替换 (带压缩)
     *
     * @param file   单个文件
     * @param oldUrl 需要替换的url地址
     * @return 返回url
     */
    public String updatePicWithCompress(MultipartFile file, String oldUrl) {
        try {
            String fileType = this.getFileType(file);
            String url = ossUtil.updateFile(file, fileType, oldUrl, 0.9f);
            if (ObjectUtil.isNullObj(url)) {
                throw new ServiceException("调用oss存储，更新/替换文件失败");
            }
            return url;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 多文件删除
     *
     * @param urls 需要删除的多文件url列表
     * @return 返回删除成功的个数
     */
    public Integer deleteFile(List<String> urls) {
        try {
            int count = ossUtil.deleteFile(urls);
            if (count <= 0) {
                throw new ServiceException("调用oss存储，批量删除同一bucket文件失败");
            }
            return count;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }


    private String getFileType(MultipartFile file) {
        return file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
    }

    /**
     * 微信上传的头像转存到OSS服务器上
     *
     * @param imgUrl
     * @return
     */
    public String wxImgToOss(String imgUrl) {
        try {

            String urlStr = "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3365018759,2226705862&fm=27&gp=0.jpg";
            String fileName = "xx.jpg";
            String savePath = "D:\\";
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(5 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
            byte[] getData = bos.toByteArray();
            //文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            System.out.println("info:" + url + " download success");


        } catch (Exception e) {
            throw new ServiceException(e.getMessage());

        }
        return null;
    }
}
